//微型模板引擎，不支持循环的
$.fn.template = function(data) {
		var template = $(this[0]).html().trim();
		if (typeof data === 'object') {
			for (var key in data) {
				template = template.replace(new RegExp('\\${' + key + '}', 'g'), data[key]);
			}
		}
		return template;
	}
	//图片防盗链
function getImgProxyUrl(img) {
	return '/img/proxy?img=' + encodeURIComponent(img);
}

App.controller('home', function(page) {
	$.getJSON('/api/4/news/latest', function(data) {
		var stories = $(page).find('#stories-template');
		var storiesUl = $(page).find('.stories-ul .ui-list');
		if (data.stories && data.stories.length) {
			for (var i = 0, n = data.stories.length; i < n; i++) {
				var storiesData = {
					title: data.stories[i].title,
					images: getImgProxyUrl(data.stories[i].images[0]),
					id: data.stories[i].id
				}
				storiesUl.append(stories.template(storiesData));
			}
		}
	})
});

App.controller('detail', function(page, args) {
	$.getJSON('/api/4/news/' + args.id, function(data) {
		var $body = $(data.body);
		$body.find('img').each(function(){
			$(this).attr('src',getImgProxyUrl($(this).attr('src')));
		});
		$body.find('.img-place-holder').css({
			'background-image':'url('+getImgProxyUrl(data.image)+')',
		});
		$(page).find('.app-title').text(data.title);
		$('.page-detail').html('');
		$('.page-detail').html($body);
	})
});
try {
	App.restore();
} catch (err) {
	App.load('home');
}
$('.fn-pannel').on('tap',function(){
	$('.stories-content').toggleClass('panel-content-wrap-open');
	$('#panel-box').toggleClass('panel-box-open');
})
